package org.example.traing.filter;




import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.traing.util.JWT;


import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebFilter(urlPatterns = "/*")
public class JwtFilter implements Filter {



    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String url = request.getRequestURL().toString();
        System.out.println("拦截成功");


  if (url.contains("manager")){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }


        String jwt = request.getHeader("token");
        if (jwt == null || jwt.isEmpty()){
            Map<String, Object> map = new HashMap<>();
            map.put("msg","not login");
            String jsonString = JSONObject.toJSONString(map);
            response.getWriter().write(jsonString);
            return;
        }

        Claims claims = JWT.parse(jwt);
        if(claims == null){
            Map<String, Object> map = new HashMap<>();
            map.put("msg","not login");
            String jsonString = JSONObject.toJSONString(map);
            response.getWriter().write(jsonString);
            return;
        }
        String uid = (String) claims.get("uid");
        servletRequest.setAttribute("uid",uid);
        filterChain.doFilter(servletRequest,servletResponse);
    }
}
